<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Image;
use Think\Db;
class ShellController extends Controller {

	//关键词首次排名
    public function getRank(){
        set_time_limit(0);
        $where['rank'] = 0;
        $where['status'] = 1;
        $where['site'] = array('neq','');
        $datalist =  M('worlddetails')->where($where)->group('site,k_id')->select();
        if(empty($datalist)){
        	exit;
        }
        foreach ($datalist as $key => $v) {
            $rank = oneRank($v['keyword'],$v['site']);
            foreach ($rank as $ks => $vs) {
                $where['seo'] = $ks;
                $where['k_id'] = $v['k_id'];
                $up['rank'] = $vs;
                $up['logtime'] = time();
                $res = M('worlddetails')->where($where)->save($up);
            }
            $result[] = $rank;
            sleep(1);
        }
        logs('关键词首次排名执行成功');
        exit;
    }


    //关键词今日排名备用  需要测试
    public function todayRanks(){
        set_time_limit(0);
        $where['status'] = 1;
        $datalist =  M('worlddetails')->where($where)->group('site,k_id')->select();
        if(empty($datalist)){
        	exit;
        }
        // var_dump($datalist);exit;
        $site = '';
        $str = '';
        foreach ($datalist as $k => $v) {
        	if($site != $v['site']){
        		$list[] = array(
        			'site' => $site,
        			'keyword' => trim($str,'|'),
        			'k_id' => $v['k_id'],
        		);
        		$str = trim($v['keyword']);
        		$site = $v['site'];
        		$k_id = $v['k_id'];
        	}else{
        		$str .= trim('|'.$v['keyword']);
        		$k_id = $v['k_id'];
        	}
        	
        }
        $list[] = ['site' => $site,'keyword' => trim($str,'|'),'k_id' => $k_id];
        array_shift($list);
        // var_dump($list);exit;
        foreach ($list as $key => $v) {
            $rank = getTaskid($v['site'],$v['keyword']);

            var_dump($rank);exit;
            // foreach ($rank as $ks => $vs) {
            //     $where['seo'] = $ks;
            //     $where['k_id'] = $v['k_id'];
            //     $up['rank'] = $vs;
            //     $up['logtime'] = time();
            //     $res = M('worlddetails')->where($where)->save($up);
            // }
            // $result[] = $rank;
        }
        exit;
    }


    //关键词今日排名
    public function todayRank(){
        set_time_limit(0);
        $where['status'] = 1;
        $logtime = strtotime(date('Y-m-d',time()));
        $where['updatelogtime'] = array('lt',$logtime);
        $where['site'] = array('neq','');
        $datalist =  M('worlddetails')->where($where)->group('site,k_id')->select();
        if(empty($datalist)){
            logs('更新的数据为空');
            echo 2333;
        	exit;
        }
        foreach ($datalist as $key => $v) {
            $rank = oneRank($v['keyword'],$v['site']);
            foreach ($rank as $ks => $vs) {
                $where['seo'] = $ks;
                $where['k_id'] = $v['k_id'];
                $where['status'] = 1;
                $up['last_rank'] = $vs;
                $up['updatelogtime'] = time();
                $data = M('worlddetails')->where($where)->find();
                if(empty($data)){
                    $where['status'] = 0;
                    $data = M('worlddetails')->where($where)->find();
                    $up['td_rank'] = $data['last_rank'];
                    $up['standard'] = $data['standard'];
                    $res = M('worlddetails')->where($where)->save($up);
                    logs(json_encode($where));
                    continue;
                }
                $up['td_rank'] = $data['last_rank'];
                $up['standard'] = $data['standard'];
                if(intval($vs) <= 10){
                	$up['standard'] = $data['standard']+1;
                    $this->charge($data,$ks);
                }
                $res = M('worlddetails')->where($where)->save($up);
            }
            $result[] = $rank;
            sleep(1);
        }
        logs('关键词今日排名执行成功');
        exit;
    }

    //客户和代理商优化关键词记录
    public function charge($data,$seo){
        $seowhere['seo'] = $seo;
        $seowhere['site'] = $data['site'];
        $seowhere['admin_id'] = $data['admin_id'];
        $seowhere['user_id'] = $data['user_id'];
        $seowhere['k_id'] = $data['k_id'];
        $where['status'] = 1;
        $result = M('worlddetails')->where($seowhere)->find();

        if(!$result){
            logs(json_encode($seowhere));
            return 0;
        }
        logs(json_encode($seowhere).'-记录关键词--'.$seowhere);
        $admin = M('admin')->where('admin_id='.$data['admin_id'])->find();
        $uwhere['admin_id'] = $data['admin_id'];
        $uwhere['user_id'] = $data['user_id'];
        $user = M('user')->where($uwhere)->find();
        $seolist = [1=>'百度PC','百度移动','360PC','360移动','搜狗PC','搜狗移动'];
        M()->startTrans();


        
        if($result && $admin['money'] > $result['amount'] && $user['money'] > $result['price']){
                


                //查询今日是否扣费过
                $logtime = strtotime(date('Y-m-d',time()));
                $chargewhere['logtime'] = array('gt',$logtime);
                $chargewhere['admin_id'] = $data['admin_id'];
                $chargewhere['amount'] = $result['amount'];
                $chargewhere['type'] = 2;
                $chargewhere['keyword_id'] = $data['k_id'];
                $chargewhere['seo'] = $result['seo'];
                $chargeList = M('charge')->where($chargewhere)->find();



                $logtime = strtotime(date('Y-m-d',time()));
                $uchargewhere['logtime'] = array('gt',$logtime);
                $uchargewhere['admin_id'] = $data['admin_id'];
                $uchargewhere['amount'] = $result['price'];
                $uchargewhere['type'] = 2;
                $uchargewhere['keyword_id'] = $data['k_id'];
                $uchargewhere['uid'] = $data['user_id'];
                $uchargewhere['seo'] = $result['seo'];
                $uchargeList = M('ucharge')->where($uchargewhere)->find();

                if($chargeList || $uchargeList){
                    logs('今日已经扣费过了');
                    return 0;
                }

                //代理商扣费
                $aup['money'] = $admin['money'] - $result['amount'];
                $aup['totalmoney'] = $admin['totalmoney'] + $result['amount'];
                $admincharge = M('admin')->where('admin_id='.$data['admin_id'])->save($aup);

                //客户扣费
                $uup['money'] = $user['money'] - $result['price'];
                $uup['totalmoney'] = $admin['totalmoney'] + $result['price'];
                $usercharge = M('user')->where($uwhere)->save($uup);
                //代理商消费实价记录
                $adata['admin_id'] = $data['admin_id'];
                $adata['amount'] = $result['amount'];
                $adata['logtime'] = time();
                $adata['type'] = 2;
                $adata['keyword_id'] = $data['k_id'];
                $adata['seo'] = $result['seo'];
                $charge = M('charge')->add($adata);
                //客户消费记录
                $udata['admin_id'] = $data['admin_id'];
                $udata['uid'] = $data['user_id'];
                $udata['amount'] = $result['price'];
                $udata['logtime'] = time();
                $udata['type'] = 2;
                $udata['keyword_id'] = $data['k_id'];
                $udata['seo'] = $result['seo'];
                $udata['desc'] = $seolist[$result['seo']].'优化《'.$data['keyword'].'》关键词扣费';
                $ucharge = M('ucharge')->add($udata);

                unset($result['id']);
                $result['updatelogtime'] = time();
                $worlddetails_log = M('worlddetails_log')->add($result);
                M()->commit();
        }else if($admin['money'] < $result['amount']){
            $when['admin_id'] = $data['admin_id'];
            $whup['status'] = 1;
            $res = M('admin')->where($when)->save($whup);
            $result = M('worlddetails')->where($when)->save($whup);
            logs('代理商余额不足');
            M()->rollback();
        }else if($user['money'] < $result['price']){
            $when['user_id'] = $data['user_id'];
            $whup['status'] = 1;
            $res = M('user')->where($when)->save($whup);
            $result = M('worlddetails')->where($when)->save($whup);
            logs('用户余额不足');
            M()->rollback();
        }else{
            logs('信息错误');
            return 0;
        }
    }

    //
    public function shell(){
        $this->daily_report();
        $this->daily_report_user();
        $this->wordStatistics();
        $title = '日报数据更新';
        $content = '这是一个测试日报数据更新的信息，如果你可以看见。那么，恭喜你。你中奖了';
        $this->sends($title,$content);
        exit;
    }


    //更新代理商日报表
    private  function daily_report(){
        try
            {   
                $sql[] = "insert into pt_daily_report (`log_date`,`admin_id`,`sitecount`,`keyworlds`) select date(from_unixtime(updatelogtime,'%Y-%m-%d %H:%i:%S')) as logdate,admin_id,count(distinct site),count(keyword) from pt_worlddetails where status =1 and site != ''  group by logdate,admin_id ON DUPLICATE KEY UPDATE sitecount=VALUES(sitecount),keyworlds=VALUES(keyworlds);";

                $sql[] = "insert into pt_daily_report (`log_date`,`admin_id`,`standard`) select date(from_unixtime(updatelogtime,'%Y-%m-%d %H:%i:%S')) as logdate,admin_id,count(last_rank) from pt_worlddetails where last_rank <=10 and last_rank > 0 and status =1 and site != '' group by logdate,admin_id,user_id ON DUPLICATE KEY UPDATE standard=VALUES(standard);";
                //客户消费sql
                $sql[] = "insert into pt_daily_report (`log_date`,`admin_id`,`pay_amount`) select date(from_unixtime(logtime,'%Y-%m-%d %H:%i:%S')) as logdate,admin_id,sum(amount) from pt_charge where type=2  group by logdate,admin_id ON DUPLICATE KEY UPDATE pay_amount=VALUES(pay_amount);";

                foreach ($sql as $key => $v) {
                    M()->execute($v);
                }
                logs('代理商日报表');
            }
            catch(Exception $e)
            {
                logs($e->getMessage());
                M()->rollback();
            }   
    }

    //更新客户日报表
    private  function daily_report_user(){
        try
            {   
                //客户关键词sql
                $sql[] = "insert into pt_daily_report_user (`log_date`,`admin_id`,`user_id`,`sitecount`,`keyworlds`) select date(from_unixtime(updatelogtime,'%Y-%m-%d %H:%i:%S')) as logdate,admin_id,user_id,count(distinct site),count(keyword) from pt_worlddetails where status =1 and site != ''  group by logdate,admin_id,user_id ON DUPLICATE KEY UPDATE sitecount=VALUES(sitecount),keyworlds=VALUES(keyworlds);";

                //客户达标sql
                $sql[] = "insert into pt_daily_report_user (`log_date`,`admin_id`,`user_id`,`standard`) select date(from_unixtime(updatelogtime,'%Y-%m-%d %H:%i:%S')) as logdate,admin_id,user_id,count(last_rank) from pt_worlddetails where last_rank <=10 and last_rank > 0 and status =1 and site != '' group by logdate,admin_id,user_id ON DUPLICATE KEY UPDATE standard=VALUES(standard);";
                //客户消费sql
                $sql[] = "insert into pt_daily_report_user (`log_date`,`admin_id`,`user_id`,`pay_amount`) select date(from_unixtime(logtime,'%Y-%m-%d %H:%i:%S')) as logdate,admin_id,uid,sum(amount) from pt_ucharge where type=2 group by logdate,admin_id,uid ON DUPLICATE KEY UPDATE pay_amount=VALUES(pay_amount);";
                foreach ($sql as $key => $v) {
                    M()->execute($v);
                }
                logs('客户日报表');
            }
            catch(Exception $e)
            {
                logs($e->getMessage());
                M()->rollback();
            }
              
    }

    //上词统计
    public function wordStatistics(){
        try
            {   
                //客户关键词sql
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`bd_keywords`,`bd_standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where seo = 1 and status = 1 and site != '' group by admin_id,user_id ON DUPLICATE KEY UPDATE bd_keywords=VALUES(bd_keywords),bd_standard=VALUES(bd_standard);";

                //客户达标sql
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`bdm_keywords`,`bdm_standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where seo = 2 and status = 1 and site != '' group by admin_id,user_id ON DUPLICATE KEY UPDATE bdm_keywords=VALUES(bdm_keywords),bdm_standard=VALUES(bdm_standard);";
                //客户消费sql
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`360_keywords`,`360_standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where seo = 3 and status = 1 and site != '' group by admin_id,user_id ON DUPLICATE KEY UPDATE 360_keywords=VALUES(360_keywords),360_standard=VALUES(360_standard);";
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`360m_keywords`,`360m_standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where seo = 4 and status = 1 and site != '' group by admin_id,user_id ON DUPLICATE KEY UPDATE 360m_keywords=VALUES(360m_keywords),360m_standard=VALUES(360m_standard);";
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`sogo_keywords`,`sogo_standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where seo = 5 and status = 1 and site != '' group by admin_id,user_id ON DUPLICATE KEY UPDATE sogo_keywords=VALUES(sogo_keywords),sogo_standard=VALUES(sogo_standard);";
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`sogom_keywords`,`sogom_standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where seo = 6 and status = 1 and site != '' group by admin_id,user_id ON DUPLICATE KEY UPDATE sogom_keywords=VALUES(sogom_keywords),sogom_standard=VALUES(sogom_standard);";
                $sql[] = "insert into pt_word_statistics (`admin_id`,`user_id`,`keywords`,`standard`) select admin_id,user_id,count(keyword),count(case when last_rank <= 10 then keyword end) as dalv from pt_worlddetails where status = 1 and site != ''  group by admin_id,user_id ON DUPLICATE KEY UPDATE keywords=VALUES(keywords),standard=VALUES(standard);";
                foreach ($sql as $key => $v) {
                    M()->execute($v);
                }
                echo 666;
            }
            catch(Exception $e)
            {
                file_put_contents('error.log',$e->getMessage().PHP_EOL,FILE_APPEND);
                echo 555;
                M()->rollback();
            }
            
    }


    //更新客户日报表
    public function demo(){
        $lbeginning  = date('Y-m-d',strtotime('-1 day'));
        var_dump($lbeginning);exit;
    }


    private function sends($title,$content){
        Vendor('phpMailer.PHPMailer');
        Vendor('phpMailer.SMTP');
        $mail = new \PHPMailer();
        // 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
        $mail->SMTPDebug = 1;
        // 使用smtp鉴权方式发送邮件
        $mail->isSMTP();
        // smtp需要鉴权 这个必须是true
        $mail->SMTPAuth = true;
        // 链接qq域名邮箱的服务器地址
        $mail->Host = 'smtp.qq.com';
        // 设置使用ssl加密方式登录鉴权
        $mail->SMTPSecure = 'ssl';
        // 设置ssl连接smtp服务器的远程服务器端口号
        $mail->Port = 465;
        // 设置发送的邮件的编码
        $mail->CharSet = 'UTF-8';
        // 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
        $mail->FromName = 'phpmailer';
        // smtp登录的账号 QQ邮箱即可
        $mail->Username = '1026393046@qq.com';
        // smtp登录的密码 使用生成的授权码
        $mail->Password = 'kkdshigaquwlbbcj';
        // 设置发件人邮箱地址 同登录账号
        $mail->From = '1026393046@qq.com';
        // 邮件正文是否为html编码 注意此处是一个方法
        $mail->isHTML(true);
        // 设置收件人邮箱地址
        // $mail->addAddress('1026393046@qq.com');
        $mail->addAddress('395241061@qq.com');
        // 添加多个收件人 则多次调用方法即可
        //$mail->addAddress('87654321@163.com');
        // 添加该邮件的主题
        // $mail->Subject = '邮件主题';
        $mail->Subject = $title;
        // 添加邮件正文
        // $mail->Body = '<h1>Hello World</h1>';
        $mail->Body = $content;
        // 为该邮件添加附件
        //$mail->addAttachment('./example.pdf');
        // 发送邮件 返回状态
        $status = $mail->send();

        return $status;
    }


    //审核之后更新字段数据
    public function  audit(){
        $this->daily_report_user();
        // echo 111;exit;
    }





}